package com.gp.shaw.netty.io.im;

import com.alibaba.fastjson.JSON;
import com.gp.shaw.netty.io.im.model.IMMsg;
import com.gp.shaw.netty.io.im.model.IMOperator;
import com.gp.shaw.netty.io.im.model.IMUser;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by asus on 2018/11/2.
 */
public class SendThread extends Thread {
    private LinkedBlockingQueue<IMMsg> msgQueue;

    private UserManager userManager;

    public SendThread(LinkedBlockingQueue<IMMsg> msgQueue, UserManager userManager){
        this.msgQueue = msgQueue;
        this.userManager = userManager;
    }

    @Override
    public void run() {
        while(true){
            if(msgQueue.size()>0) {
                IMMsg msg = msgQueue.poll();
                if (msg != null) {
                    //执行发送
                    switch (msg.getOperator()) {
                        case IMOperator.SEND_PERSON:
                            sendToPerson(msg);
                            break;

                        case IMOperator.SEND_GROUP:
                            sendToGroup(msg);
                            break;
                    }
                }
            }
        }
    }

    /**
     * 发送给个人
     */
    private void sendToPerson(IMMsg msg){
        IMUser targetUser = userManager.getUser(msg.getTarget());
        if(targetUser==null){
            return;
        }
        sendMsg(msg,targetUser);
    }

    /**
     * 发送给小组
     */
    private void sendToGroup(IMMsg msg){
        String groupId = msg.getTarget();
        List<IMUser> users = userManager.getUserByGroup(msg.getTarget());
        if(users!=null&&users.size()>0){
            users.stream().forEach(user->{
                sendMsg(msg,user);
            });
        }
    }

    /**
     * 发送消息
     * @param msg
     * @param user
     * @return
     */
    private boolean sendMsg(IMMsg msg,IMUser user){

        Socket socket = user.getSocket();
        if(socket==null||socket.isClosed()){
            System.out.println("socket已关闭，无法发送消息");
            return false;
        }
        ObjectOutputStream oos= null;
        try {
            oos = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try{
            oos.writeObject(msg);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}
